package web.admin.shop.product.checkboxtree;

import org.apache.wicket.markup.html.tree.DefaultTreeState;

import javax.swing.tree.TreeNode;

public class CategoryTreeState extends DefaultTreeState {

    public void collapseNode(TreeNode node) {

        super.collapseNode(node);
    }

    public void expandNode(TreeNode node) {
        checkNodeChildren(node);
        super.expandNode(node);

    }

    public boolean isNodeExpanded(TreeNode node) {
        if (node.getChildCount() == 0) {
            return false;
        } else {
            return super.isNodeExpanded(node);
        }
    }

    public void selectNode(TreeNode node, boolean selected) {
        checkNodeChildren(node);
        super.selectNode(node, selected);
    }

    private void checkNodeChildren(TreeNode node) {
        if (node instanceof RootTreeNode) {
            RootTreeNode rnode = (RootTreeNode) node;
            if (rnode.getChildCount() == 0) {
                rnode.loadChildren();
            }
        } else if (node instanceof CategoryTreeNode) {
            CategoryTreeNode cnode = (CategoryTreeNode) node;
            if (cnode.getChildCount() == 0) {
                cnode.loadChildren();
            }
        }
    }
}
